//
//  ViewController.m
//  Care With Friends
//
//  Created by Versatile Systems, Inc on 11/1/13.
//  Copyright (c) 2013 Muludiang. All rights reserved.
//

#import "ViewController.h"
#import "CWFData.h"
#import "LandingPageViewController.h"

@interface ViewController ()

@end

@implementation ViewController

@class CWFData;

@synthesize userName;
@synthesize password;
@synthesize email;
@synthesize loadingActivity;
@synthesize signInBtn;
@synthesize rememberMeBtn;

-(IBAction)hideKeyboard:(id)sender{
    [userName resignFirstResponder];
    [password resignFirstResponder];
    [email resignFirstResponder];
}

-(IBAction)logMeIn:(id)sender{
    [userName resignFirstResponder];
    [password resignFirstResponder];
    [email resignFirstResponder];
    if (([[userName.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] == 0) || ([[userName.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] == 0) || ([[password.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] == 0)){
        UIAlertView *errorAlert = [[UIAlertView alloc]
                                   initWithTitle:@"Oops.." message:@"Please check that you entered a NT Username, password and email address"
                                   delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [errorAlert show];

    }
    else{
    CWFData *dataObj = [CWFData sharedInstance];
    dataObj.currentRequest = [NSString stringWithFormat:@"notAuthenticated"];
    dataObj.CWFlogin = userName.text;
    dataObj.CWFpassword = password.text;
    dataObj.CWFemail = email.text;
    [dataObj connectWithUserPass:[dataObj CWFlogin] emailAddr:[dataObj CWFemail] password:[dataObj CWFpassword]];
    [loadingActivity startAnimating];
    }
}

-(void)gotoMainMenu:(NSNotification *)notification{
    if ( [[notification name] isEqualToString:@"loadingFinished"])
    {
 NSLog(@"All done!!!");
        finished = YES;
        [[NSNotificationCenter defaultCenter] removeObserver:self
                                                        name:@"loadingFinished"
                                                      object:nil];
        //[self dismissViewControllerAnimated:YES completion:nil];
        [self performSegueWithIdentifier:@"landing_segue" sender:self];
        [loadingActivity stopAnimating];
        NSLog(@"Here we go...");
    }
}

-(BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender{
    return finished;
}

-(void)rememberMe:(id)sender{
    NSLog(@"Switch used");
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    
    if (![sender isOn]){
        [defaults setValue:@"" forKey:@"username_preference"];
        [defaults setValue:@"" forKey:@"email_preference"];
    }else{
        if (([[userName.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] == 0) || ([[userName.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] == 0)){
            UIAlertView *errorAlert = [[UIAlertView alloc]
                                       initWithTitle:@"Oops.." message:@"Please provide a NT Username and email address"
                                       delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [errorAlert show];
            [rememberMeBtn setOn:NO];
        }
        else{
            [defaults setValue:userName.text forKey:@"username_preference"];
            [defaults setValue:email.text forKey:@"email_preference"];
        }
    }

}

-(void)dealloc{
    //CWFData *dataObj = [CWFData sharedInstance];

}

- (void)viewDidLoad
{

    UIToolbar *toolbar = [[UIToolbar alloc] init];
    [toolbar setBarStyle:UIBarStyleBlackTranslucent];
    [toolbar sizeToFit];
    
    UIBarButtonItem *flexButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    UIBarButtonItem *doneButton =[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(hideKeyboard:)];
    
    NSArray *itemsArray = [NSArray arrayWithObjects:flexButton, doneButton, nil];
    
    [toolbar setItems:itemsArray];
    
    [userName setInputAccessoryView:toolbar];
    [password setInputAccessoryView:toolbar];
    [email setInputAccessoryView:toolbar];


    [super viewDidLoad];
    //CWFData *dataObj = [CWFData sharedInstance];
	// Do any additional setup after loading the view, typically from a nib.
    UIImage *buttonImage = [[UIImage imageNamed:@"blackButton.png"]
                            resizableImageWithCapInsets:UIEdgeInsetsMake(18, 18, 18, 18)];
    UIImage *buttonImageHighlight = [[UIImage imageNamed:@"blackButtonHighlight.png"]
                                     resizableImageWithCapInsets:UIEdgeInsetsMake(18, 18, 18, 18)];
    // Set the background for any states you plan to use
    [signInBtn setBackgroundImage:buttonImage forState:UIControlStateNormal];
    [signInBtn setBackgroundImage:buttonImageHighlight forState:UIControlStateHighlighted];
    finished = NO;

}


-(void)textFieldDidBeginEditing:(UITextField *)textField{
    if (textField.tag == 2) {
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.35f];
        CGRect frame = self.view.frame; frame.origin.y = -125;
        [self.view setFrame:frame];
        [UIView commitAnimations];
    } else if (textField.tag == 3) {
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.35f];
        CGRect frame = self.view.frame; frame.origin.y = -150;
        [self.view setFrame:frame];
        [UIView commitAnimations];
    }
}

-(void)textFieldDidEndEditing:(UITextField *)textField{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.35f];
    CGRect frame = self.view.frame; frame.origin.y = 0;
    [self.view setFrame:frame];
    [UIView commitAnimations];
}


-(void)viewDidAppear:(BOOL)animated{
    [[NSNotificationCenter defaultCenter ] addObserver:self
                                              selector:@selector(gotoMainMenu:)
                                                  name:@"loadingFinished"
                                                object:Nil];
    [rememberMeBtn addTarget:self action:@selector(rememberMe:) forControlEvents:UIControlEventValueChanged];
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    
    if (([[[defaults valueForKey:@"username_preference"] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] > 0) && ([[[defaults valueForKey:@"username_preference"] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] > 0)){
        userName.text = [defaults valueForKey:@"username_preference"];
        email.text = [defaults valueForKey:@"email_preference"];
        [rememberMeBtn setOn:YES animated:YES];
    }
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
